package com.rivues.module.manage.web.handler.system;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.User;
import com.rivues.util.RivuTools;
import com.rivues.util.service.distributed.DeleteFileTask;
import com.rivues.util.tools.RuntimeData;

@Controller
@RequestMapping("/{orgi}/manage/file")
public class FileController extends Handler {
	private final Logger log = LoggerFactory
			.getLogger(FileController.class);

	/**
	 * 
	 * @param request
	 * @param orgi
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index", name = "index", type = "manage", subtype = "files")
	public ModelAndView servicesetting(HttpServletRequest request,@PathVariable String orgi, @Valid String ex)
			throws Exception {
		ModelAndView modelView = request(
				super.createManageTempletResponse("/pages/manage/system/filelist"),
				orgi);
		if(ex!=null){
			modelView.addObject("ex", ex);
		}
		/**
		 * 文件系统存放的文件列表
		 */
		File[] jobsListFiles = RivuTools.getDefaultExportJobPath(orgi).listFiles() ;
		List<JobDetail> jobList = new ArrayList<JobDetail>();
		for(File job : jobsListFiles){
			if(job.length()>0){
				/**
				 * 增加过滤器
				 */
		    	JobDetail jobDetail = (JobDetail) RivuTools.toObject(FileUtils.readFileToByteArray(job)) ;
		    	
		    	
		    	String beginTime = request.getParameter("beginTime");
	    		String endTime = request.getParameter("endTime");
	    		modelView.addObject("beginTime",beginTime);
	    		modelView.addObject("endTime",endTime);
		    	//用户检索
		    	 
		    	String userid = request.getParameter("userid");
		    	if(userid!=null&&!"".equals(userid)){
		    		String username = request.getParameter("username");
		    		if(username==null){
		    			List<User> users = RivuDataContext.getOnlineUser();
		        		User user = null;
		        		for (int i = 0; i < users.size(); i++) {
		    				user = users.get(i);
		    				if(userid.equals(user.getId())){
		    					username = user.getUsername();
		    				}
		    			}
		        		modelView.addObject("uid",userid);
		    		}
		        	modelView.addObject("username",username);
		        	if(jobDetail.getUserid()!=null && !jobDetail.getUserid().equals(userid)){
		        		continue ;
		        	}
		    	}
		    	modelView.addObject("userid",userid);
		    	
		    	
		    	//报表检索
		    	String reportid = request.getParameter("reportid");
		    	modelView.addObject("reportid",reportid);
		    	String reportname = request.getParameter("reportname");
		    	modelView.addObject("reportname",reportname);
		    	if(reportid!=null && reportid.length()>0){
			    	if(jobDetail.getDataid()!=null && !jobDetail.getDataid().equals(reportid)){
		        		continue ;
		        	}
		    	}
		    	
		    	//报表目录检索
		    	String dicid = request.getParameter("dicid");
		    	modelView.addObject("dicid",dicid);
		    	String dicname = request.getParameter("dicname");
		    	modelView.addObject("dicname",dicname);
		    	
		    	String priority = request.getParameter("priority");
		    	modelView.addObject("priority",priority);
		    	String status = request.getParameter("status");
		    	if(status!=null&&!"".equals(status)){
		    		if("1".equals(status)){//正在执行
//		    			criteria.add(Restrictions.eq("fetcher",true));
//		    		}else if("2".equals(status)){//等待中		
//		    			criteria.add(Restrictions.eq("taskstatus","1"));
		    		}else{//已挂起
//		    			criteria.add(Restrictions.eq("pause",true));
		    		}
		    	}
		    	
		    	if(beginTime!=null && beginTime.length()>0){
	    			Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginTime) ;
	    			if(jobDetail.getLastdate()!=null && jobDetail.getLastdate().before(startDate)){
	    				continue ;
	    			}
	    		}
	    		if(endTime!=null && endTime.length()>0){
	    			Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime) ;
	    			if(jobDetail.getLastdate()!=null && jobDetail.getLastdate().after(endDate)){
	    				continue ;
	    			}
	    		}
	    		File dataFileNotExp = RivuTools.getExportFile(orgi, jobDetail.getId()) ;	//data file
	    		if(dataFileNotExp == null){
	    			jobDetail.setMetadata(true);// guo qi
	    		}
	    		File dataFile = RivuTools.getExportFileWithOutTimeOut(orgi, jobDetail.getId()) ;
	    		jobDetail.setLastindex(0);
	    		if(dataFile.exists()){
	    			jobDetail.setLastindex(dataFile.length());
	    		}
	    		jobDetail.setMemo(RivuTools.dateToString(new Date(job.lastModified()), "yyyy年MM月dd HH:mm:ss")) ;
	    		jobDetail.setOrgi(Double.parseDouble(new Date(job.lastModified()).getTime()-jobDetail.getNextfiretime().getTime()+"")/1000+"秒");
				jobList.add(jobDetail) ;
			}
			
		}
		
		modelView.addObject("storagepath",RuntimeData.getStoragepath());
		modelView.addObject("storagesize",RuntimeData.getStoragesize());
		modelView.addObject("storagemax",RuntimeData.getStoragemax());
		modelView.addObject("storagefiles",RuntimeData.getStoragefiles());
		modelView.addObject("lastcheck",RuntimeData.getLastcheck());	
		
    	modelView.addObject("exportFiles", jobList) ;
		return modelView;
	}
	
	@RequestMapping(value = "/delete", name = "delete", type = "manage", subtype = "files")
	public ModelAndView delete(HttpServletRequest request,@PathVariable String orgi, @Valid String keyid)
			throws Exception {
		ModelAndView modelView = request(
				super.createManageResponse("redirect:/{orgi}/manage/file/index.html"),
				orgi);
		new DeleteFileTask(keyid , orgi).call() ;
		return modelView ;
	}

}